/*
 *    Copyright 2009-2010 The iBaGuice Team
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.google.code.ibaguice.plugins.validation;

import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;

import com.google.inject.Inject;

/**
 * Argument validation plugin.
 *
 * @author Simone Tripodi
 * @version $Id: ValidationInterceptor.java 1866 2010-02-28 11:19:28Z simone.tripodi $
 */
@Intercepts({ @Signature(
        type = ParameterHandler.class,
        args = { Object.class },
        method = "update"
) })
public final class ValidationInterceptor implements Interceptor {

    /**
     * The Validator reference.
     */
    private final Validator validator;

    /**
     * Build a new Validation plugin given the Validator reference.
     *
     * @param validator the Validator reference
     */
    @Inject
    public ValidationInterceptor(Validator validator) {
        this.validator = validator;
    }

    /**
     * {@inheritDoc}
     */
    public Object intercept(Invocation invocation) throws Throwable {
        Set<ConstraintViolation<Object>> constraintViolations = new HashSet<ConstraintViolation<Object>>();
        for (Object obj : invocation.getArgs()) {
            constraintViolations.addAll(this.validator.validate(obj));
        }

        if (!constraintViolations.isEmpty()) {
            // TODO looking for a nice way to throw exceptions here
            System.err.println(constraintViolations);
        }

        return invocation.proceed();
    }

    /**
     * {@inheritDoc}
     */
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    /**
     * {@inheritDoc}
     */
    public void setProperties(Properties properties) {
        // not supported in this version
    }

}
